<template>
  <!-- 新建/修改工艺版本 -->
  <el-dialog
    width="1200px"
    :close-on-click-modal="false"
    :title="title"
    class="addProcessDetail-dialog"
    :visible.sync="dialogVisible"
    append-to-body
    @close="close"
  >
    <el-form ref="form" :model="data" :rules="rules">
      <el-row class="text-center">
        <el-col :span="7">
          <h3>版本名称：{{ basics.versionName }}</h3>
          <!--
          <el-form-item prop="area" label="版本名称">
            <el-input
              v-model="basics.versionName"
              class="w150"
              placeholder="工艺版本"
              disabled
              clearable
            ></el-input>
          </el-form-item>
          -->
        </el-col>
        <el-col :span="7">
          <h3>图号：{{ basics.drawingNumber }}</h3>
          <!--
          <el-form-item prop="name" label="图号">
            <el-input class="w150" v-model="basics.drawingNumber" placeholder="图号" disabled></el-input>
          </el-form-item>
          -->
        </el-col>
        <el-col :span="7">
          <h3>产品名称：{{ basics.productName }}</h3>
        </el-col>
        <!--
        <el-col :span="4">
          <el-form-item>
            <el-switch
              v-model="formDetail.nn"
              active-color="#13ce66"
              active-text="整体外协"
              @change="overAll"
            ></el-switch>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item prop="type">
            <el-select
              v-if="!over"
              v-model="basics.supplier"
              class="w150"
              filterable
              placeholder="外协供应商"
              clearable
            >
              <template v-for="item in supplierList">
                <el-option :key="item" :label="item" :value="item"></el-option>
              </template>
            </el-select>
          </el-form-item>
        </el-col>
        -->
      </el-row>
      <div>
        <el-row class="mt0">
          <el-form-item class="w-100percent bold bg-lightGray mb5">
            输入工序信息
            <el-button
              v-if="!isEditProcess"
              @click="addProcess()"
              type="text"
              icon="el-icon-plus"
              size="small"
            >添加工序</el-button>
            <el-button
              v-else
              @click="confirmProcess"
              type="text"
              icon="el-icon-check"
              size="small"
              class="color-hdbl"
            >确认工序</el-button>
          </el-form-item>
        </el-row>
        <el-row class="mb10" v-if="isEditProcess">
          <el-col :span="3">
            <el-form-item class="mb0" prop="sequenceNumber" label="工序号">
              <el-input class="w-50percent" v-model="data.sequenceNumber" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item class="mb0" prop="processName" label="工序名称">
              <el-select
                class="w150"
                v-model="data.processName"
                @change="processNameChange"
                filterable
              >
                <template v-for="option in processNameList">
                  <el-option :key="option" :label="option" :value="option"></el-option>
                </template>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item
              v-if="data.processName != '完工'"
              class="mb0"
              prop="department"
              label="部门/执行"
            >
              <el-select
                class="w150"
                v-model="data.department"
                filterable
                @change="onChangeDepartment"
              >
                <template v-for="option in options">
                  <el-option :key="option" :label="option" :value="option"></el-option>
                </template>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col v-if="data.processName != '完工' && data.department != '加工'" :span="6">
            <el-form-item class="mb0" prop="area" label="供应商">
              <el-select class="w150" v-model="data.supplier" clearable filterable>
                <template v-for="option in supplierList">
                  <el-option :key="option" :label="option" :value="option"></el-option>
                </template>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col v-if="data.department == '加工'" :span="6">
            <el-switch
              v-model="data.single"
              active-text="单机"
              inactive-text="双机"
              active-color="#004098"
              @change="changeMul"
              class="mt10"
            ></el-switch>
          </el-col>
        </el-row>
        <div v-if="data.department == '加工' && isEditProcess" class="mb10">
          <el-form-item class="w-100percent mb0">
            输入设备信息
            <!-- <el-button @click="addEquit()" type="text" icon="el-icon-plus" size="small"
              >添加设备</el-button
            >-->
          </el-form-item>
          <hr style="margin-block-start: 0em" />
          <template v-for="(item, eIndex) in data.equipmentList">
            <el-row :key="eIndex">
              <el-col :span="5">
                <el-form-item class="no-margin" label="设备名称">
                  <el-select
                    class="w150"
                    v-model="item.equipment"
                    clearable
                    :multiple-limit="maxEquitment"
                    multiple
                    filterable
                    placeholder="请选择设备名称"
                  >
                    <template v-for="(option, oIndex) in equipmentList">
                      <el-option :key="oIndex" :label="option" :value="option"></el-option>
                    </template>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item class="no-margin" label="调试工时" :prop="'equipmentList.' + eIndex + '.debugHour'" :rules="rules.debugHour">
                  <el-input class="w150" v-model="item.debugHour"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item class="no-margin" label="定额工时" :prop="'equipmentList.' + eIndex + '.quotaHour'" :rules="rules">
                  <el-input class="w150" v-model="item.quotaHour"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item>
                  <el-button
                    @click="addEquit()"
                    type="text"
                    icon="el-icon-plus"
                    size="small"
                    v-if="(equitListLen - 1) == eIndex"
                  >添加设备</el-button>
                  <el-button
                    @click="deleteEquit(eIndex)"
                    type="text"
                    icon="el-icon-delete"
                    size="small"
                    v-else
                  >移除该设备</el-button>
                </el-form-item>
              </el-col>
            </el-row>
          </template>
        </div>
      </div>
      <el-form-item class="w-100percent bold bg-lightGray mb5 mt20">工艺表</el-form-item>
      <el-table
        class="mt0"
        border
        stripe
        ref="multipleTable"
        :span-method="merge"
        :data="processList"
        row-key="sid"
        :default-sort="{ prop: 'sequenceNumber', order: 'ascending' }"
        default-expand-all
        :tree-props="{ children: 'equipmentList', hasChildren: 'hasChildren' }"
      >
        <el-table-column prop="sequenceNumber" label="序号" align="right" width="80"></el-table-column>
        <el-table-column prop="processName" label="工序名称" align="left" width="180"></el-table-column>
        <el-table-column prop="department" label="部门/执行" align="center" width="120"></el-table-column>
        <el-table-column prop="supplier" label="供应商" align="center" width="180"></el-table-column>
        <el-table-column prop="single" label="单双机" align="center" width="100">
          <template slot-scope="scope" v-if="scope.row.department == '加工'">
            <div>{{ scope.row.single ? "单机" : "双机" }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="equipment" label="设备" align="center" width="180"></el-table-column>
        <el-table-column prop="debugHour" label="调试工时" align="center" width="110"></el-table-column>
        <el-table-column prop="quotaHour" label="定额工时" align="center" width="110"></el-table-column>
        <el-table-column label="操作" align="left" fixed="right" width="100">
          <template slot-scope="scope" v-if="scope.row.sequenceNumber">
            <i
              class="iconfont icon-xiugai1"
              @click="editProcess(scope.row, scope.row.sequenceNumber)"
            ></i>
            <i class="iconfont icon-shanchu1" @click="delProcess(scope.row)"></i>
          </template>
        </el-table-column>
      </el-table>
    </el-form>

    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="save">提交</el-button>
      <el-button @click="close">关闭</el-button>
    </div>
  </el-dialog>
</template>

<script lang="ts">
import { Vue, Component } from "vue-property-decorator";
import { State, namespace } from "vuex-class";
import AddProduct from "./addProduct.vue";
import _ from 'lodash'

const vuexProcess = namespace("TwoProcess");

@Component({
  components: {
    AddProduct,
  },
})
export default class EditProcessDetail extends Vue {
  public $refs!: {
    form: any;
    multipleTable: any;
    addproduct: any;
  };

  validateWorkHour:any = (rule, value, callback) => {
    let partten = /^([0-9]*)+(\.[0-9]{1,2})?$/
    console.log(value)
    console.log(rule)
    
    if (!partten.test(value)) {
      callback(new Error('正确格式：0-2位小数'))
    } else {
      callback();
    }
  }

  rules: any = {
    quotaHour: [
      { required: true, trigger: 'change', validator: this.validateWorkHour },
    ],
    debugHour: [
      { required: true, trigger: 'change', validator: this.validateWorkHour },
    ]
  }



  @vuexProcess.State sixSearch: any;
  @vuexProcess.State addId: any;
  @vuexProcess.State addName: any;
  @vuexProcess.State supplierList: any;
  //supplierList: any[] = ['gongyings1', 'gonggsad2', 'gjerf']
  @vuexProcess.State equipmentList: any;
  //equipmentList: any[] = ['sheb', 'shbhjk', 'safghwe']
  @vuexProcess.State processNameList: any;
  //processNameList: any[] = ['ghj', 'g', 'gh', 'fg', '完工', '清整']
  @vuexProcess.State processDetailList: any;

  // @vuexProcess.Action  PREEDIT_VERSION: any
  @vuexProcess.Action GET_VERSION: any;
  @vuexProcess.Action PREDATA_VERSION: any;
  @vuexProcess.Action updata_VERSION: any;
  @vuexProcess.Action GET_PROCESS_DATEBASE: any;


  versionId: string = "";
  title: string = "新增工艺版本";
  dialogVisible: boolean = false;
  //整体外协
  over: boolean = true;

  //删除使用标识
  sid: string = "";
  //key sid
  id: number = 20;
  //设备多选
  maxEquitment: number = 1;
  //提交的表单数组
  requestList: any[] = [];
  // DEquit: boolean = true;
  //输入内容

  data: any = {
    sid: "",
    sequenceNumber: "",
    processName: "",
    department: "",
    supplier: "",
    single: false,
    equipmentList: [
      {
        sid: "",
        id: 3,
        equipment: "",
        debugHour: "",
        quotaHour: "",
      },
    ],
  };

  formDetail: any = {
    nn: false,
  };
  basics: any = {
    drawingNumber: "",
    versionName: "",
    productName: "",
    supplier: "",
  };

  processList: any[] = [
    // {
    //   sid: 1,
    //   sequenceNumber: "1",
    //   processName: "",
    //   department: "",
    //   supplier: "",
    //   single: true,
    //   equipmentList: [],
    // },
  ];
  mulNumber: number = 2// 双机可选的设备数
  options: any[] = ["采购", "加工", "外协"];
  isEditProcess: boolean = false;
  curEditIndex: any = 0;// 当前被编辑/添加的工序的Index

  //新增工艺版本进来
  getAdd(drawingNumber: string, versionName: string) {
    this.basics.drawingNumber = drawingNumber;
    this.basics.versionName = versionName;
    this.basics.productName = this.addName;
    this.versionId = this.addId;
  }
  //设计修改进来
  async getData(drawingNumber, productName, versionName, versionId, arr) {
    this.title = "修改工艺版本";
    this.basics.drawingNumber = drawingNumber;
    this.basics.versionName = versionName;
    this.basics.productName = productName;
    this.processList = arr;
    this.versionId = versionId;
    let result = await this.GET_VERSION({ versionId: this.versionId });
    let getData = await this.PREDATA_VERSION({ versionId: this.versionId });
    if (result && getData) {
      this.newArr(this.processNameList);
      this.newArr(this.equipmentList);
      this.newArr(this.supplierList);
      //  this.List = this.equipmentList
      this.dialogVisible = true;
    }
  }
  //新增进来
  open(isNew) {
    this.title = "新增工艺版本";

    this.newArr(this.equipmentList);
    this.newArr(this.supplierList);
    this.newArr(this.processNameList);
    // this.List = this.equipmentList
    this.dialogVisible = true;
  }
  //修改进来
  async openEdit(id: any, versionName: any, drawingNumber: any, productName: any) {
    this.title = "修改工艺版本";
    this.newArr(this.processNameList);
    this.newArr(this.equipmentList);
    this.newArr(this.supplierList);
    //  this.List = this.equipmentList
    this.versionId = id;
    this.basics.versionName = versionName;
    this.basics.drawingNumber = drawingNumber;
    this.basics.productName = productName;
    this.processList = this.processDetailList[0].processList;
    this.addSid();
    this.dialogVisible = true;
  }
  addProcess() {
    this.isEditProcess = true
    const add = {
      sid: "",
      sequenceNumber: "1",
      processName: "",
      department: "",
      equipmentList: [],
      single: true,
      supplier: "",
    };
    let index = this.curEditIndex = this.processList.length;
    add.sid = 'a' + index;
    add.sequenceNumber = (index + 1).toString();
    this.data = add;
  }

  addEquit() {
    const add = {
      sid: "",
      equipment: [],
      debugHour: "",
      quotaHour: "",
    };
    //需要全局变量
    add.sid = 'b' + this.curEditIndex + this.data.equipmentList.length;
    this.data.equipmentList.push(add);
  }
  //删除设备新函数 0714
  deleteEquit(eIndex) {
    this.data.equipmentList.splice(eIndex, 1);
    this.data.equipmentList = this.data.equipmentList.map((item, index) => {
      item.sid = 'b' + this.curEditIndex + index
      return item;
    })
  }

  //数组去重
  newArr(arr) {
    for (var i = 0; i < arr.length; i++) {
      for (var j = i + 1; j < arr.length; j++) {
        if (arr[i] == arr[j]) {
          //如果第一个等于第二个，splice方法删除第二个
          arr.splice(j, 1);
          j--;
        }
      }
    }
    return arr;
  }

  processNameChange(process) {
    if (process == "完工") {
      this.data.supplier = '';
      this.data.equipmentList = [];
      this.data.department = '';
    }
  }
  //更换 设备/供应商的选择列表
  onChangeDepartment(data) {
    if (data == "加工" && this.data.equipmentList.length == 0) {
      this.data.equipmentList = [{
        sid: "",
        equipment: [],
        debugHour: 0,
        quotaHour: 0,
      }]
      this.data.equipmentList[0].sid = 'b' + this.curEditIndex + '0';
    } else {
      this.data.equipmentList = [];
    }
  }

  //选择双击设备
  changeMul(isSingle) {
    // console.log(data)
    if (isSingle) {// 单机
      this.maxEquitment = 1;
    } else {// 双机
      this.maxEquitment = 2;
    }
  }
  //是否整体外协
  // overAll(data) {
  //   if (data) {
  //     this.over = false;
  //   } else {
  //     this.over = true;
  //   }
  // }
  save() {
    if (this.isEditProcess) {
      this.confirmProcess();
    }
    if (this.title === "新增工艺版本") {
      this.changeData();
      this.Create();
    }
    if (this.title === "修改工艺版本") {
      this.changeData();
      this.Edit();
    }
  }
  async Create() {
    let result = await this.updata_VERSION({
      versionId: this.versionId,
      processList: this.requestList,
    });
    if (result) {
      console.log('新建 update')
      this.$emit('update')
      this.close();
    }
  }
  async Edit() {
    let result = await this.updata_VERSION({
      versionId: this.versionId,
      processList: this.requestList,
    });
    if (result) {
      console.log('修改 update')
      this.$emit('update')
      this.close();
    } else {
      this.preUpdate();
    }
  }
  async preUpdate() {// 修改不成功，重新获取原始数据
    let result = await this.GET_VERSION({ versionId: this.versionId });
    if (result) {
      this.processList = this.processDetailList[0].processList;
      this.addSid();
    }
  }

  close() {
    // this.GET_PROCESS_DATEBASE({ ...this.sixSearch });
    //初始化表格
    this.processList = [
      {
        sid: 1,
        sequenceNumber: "1",
        processName: "",
        department: "",
        supplier: "",
        single: true,
        equipmentList: [],
      },
    ];
    // this.over = true;
    this.versionId = "";

    //设备多选
    this.maxEquitment = 1;
    //提交的表单数组
    this.requestList = [];
    /*
     //整体外协
    this.formDetail = {
      nn: false
    }
    */
    //this.$refs.form.resetFields()
    this.dialogVisible = false;
    this.$refs.form.resetFields();
    this.initData();
  }

  //添加row-key
  addSid() {
    this.processList = this.processList.map((pItem, pIndex) => {
      pItem.sequenceNumber = pIndex + 1;
      this.$set(pItem, 'sid', 'a' + pIndex);
      if (pItem.equipmentList) {
        pItem.equipmentList = pItem.equipmentList.map((eItem, eIndex) => {
          this.$set(eItem, 'sid', 'b' + pIndex + eIndex);
          return eItem;
        })
      }
      return pItem;
    })
  }

  //新增的 数据移到新数组
  changeData() {
    this.requestList = _.cloneDeep(this.processList)
    this.requestList = this.requestList.map((pItem, pIndex) => {
      delete pItem.sid
      delete pItem.sequenceId
      delete pItem.versionId
      pItem.equipmentList = pItem.equipmentList.map(eItem => {
        delete eItem.sid
        delete eItem.id
        return eItem;
      })
      return pItem;
    })
  }

  //生产随机数
  random(lower, upper) {
    return Math.floor(Math.random() * (upper - lower)) + lower;
  }
  //加工合并行
  merge({ row, column, rowIndex, columnIndex }) {
    //  console.log(row,row.equipment)

    if (!row.sequenceNumber) {
      if (columnIndex === 1) {
        return [1, 3];
      } else if (columnIndex === 2) {
        return [0, 0];
      } else if (columnIndex === 3) {
        return [0, 0];
      }
      //设置加号不展示
    }
  }
  editProcess(row, index) {
    this.curEditIndex = index - 1;
    this.maxEquitment = row.single ? 1 : 2
    this.data = _.cloneDeep(row);
    this.transformEquitToArr();
    this.isEditProcess = true;
  }
  delProcess(row) {
    this.$confirm(`是否移除工序${row.sequenceNumber}-${row.processName}?`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      this.processList.splice(row.sequenceNumber - 1, 1);
      this.addSid();
      this.isEditProcess = false;
    }).catch(() => {
    });
  }
  confirmProcess() {
    // 确认工序
    let flag = this.transformEquitToStr();
    if (flag) {
      this.isEditProcess = false;
      this.processList.splice(this.curEditIndex, 1, this.data)
    }
  }
  get equitListLen() {
    return this.data.equipmentList.length;
  }
  initData() {
    this.isEditProcess = false;
    this.data = {
      sequenceNumber: "",
      processName: "",
      department: "",
      supplier: "",
      single: false,
      equipmentList: [],
    }
  }
  transformEquitToArr() {
    this.data.equipmentList = this.data.equipmentList.map(item => {
      item.equipment = item.equipment.split(';')
      return item;
    })
  }
  transformEquitToStr() {
    let flag = true;
    this.data.equipmentList = this.data.equipmentList.map(item => {
      if (this.data.department == '加工') {
        if (this.data.single && item.equipment.length != 1) {
          this.$message.warning('单机工序只能选择一台设备')
          flag = false
        } else if ((!this.data.single) && item.equipment.length != this.mulNumber) {
          this.$message.warning('双机工序只能选择两台设备')
          flag = false
        } else {
          item.equipment = item.equipment.join(';')
        }
      } else {
        item.equipment = item.equipment.join(';')
      }
      return item;
    })
    return flag;
  }
}
</script>

<style lang="scss">
.addProcessDetail-dialog {
  .icon-xiugai1:before {
    font-size: 12px;
  }
  .icon-shanchu1:before {
    font-size: 12px;
  }
  .el-switch__label.is-active > span {
    font-weight: bold;
    font-size: 18px;
  }
}
</style>
